package com.example.wan_android.ui.fragment

import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.example.wan_android.BR
import com.example.wan_android.R
import com.example.wan_android.adapter.MainBannerAdapter
import com.example.wan_android.adapter.PaperAdapter
import com.example.wan_android.databinding.FragmentPaperShowBinding
import com.example.wan_android.tools.SpacesItemDecoration
import com.example.wan_android.viewmodel.PaperShowViewModel

class PaperShowFragment : BaseFragment<FragmentPaperShowBinding, PaperShowViewModel>(
    PaperShowViewModel::class.java,
    R.layout.fragment_paper_show,
    BR.viewModel
) {
    private val handle = Handler(Looper.getMainLooper())
    private val bannerAdapter by lazy {
        MainBannerAdapter(viewLifecycleOwner, mViewModel!!)
    }
    private val paperAdapter by lazy {
        PaperAdapter(mViewModel!!)
    }

    override fun onResume() {
        super.onResume()
        mViewModel?.isSuccess?.observe(this) {
            if (it) {
                mViewDataBinding?.ivEmpty?.visibility = View.GONE
                mViewDataBinding?.rvPaperItem?.visibility = View.VISIBLE
            } else {
                mViewDataBinding?.ivEmpty?.visibility = View.VISIBLE
                mViewDataBinding?.rvPaperItem?.visibility = View.GONE
            }
        }
        triggerReload() // 每次Fragment可见时触发刷新
    }

    private fun triggerReload() {
        // 1. 清理旧数据
        paperAdapter.clear()

        // 2. 重新加载核心数据
        mViewModel?.apply {
            position = 0
            getPaperInfoData() // 加载文章数据
        }

    }


    override fun initViews() {
        mViewDataBinding?.init()
        mViewModel?.isSuccess?.observe(this) {
            if (it) {
                mViewDataBinding?.ivEmpty?.visibility = View.GONE
                mViewDataBinding?.rvPaperItem?.visibility = View.VISIBLE
            } else {
                mViewDataBinding?.ivEmpty?.visibility = View.VISIBLE
                mViewDataBinding?.rvPaperItem?.visibility = View.GONE
            }
        }
        mViewModel?.banners?.observe(this) {
            it.onSuccess {
                bannerAdapter.setListData(it)
            }
        }
        banner()
        mViewModel?.getPaperInfoData()
        mViewModel?.paperInfoData?.observe(this) {
            it.onSuccess {
                paperAdapter.addListData(it)
            }
            it.onFailure {
                Log.i("TAG", "initViews: " + it.message)
            }
        }
        mViewDataBinding?.nvNestedScroll?.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            if (isNearBottom(scrollY)) {
                mViewModel?.getPaperInfoData()
            }
        })
    }

    // 判断是否接近底部
    private fun isNearBottom(scrollY: Int): Boolean {
        val contentHeight = mViewDataBinding?.nvNestedScroll?.getChildAt(0)?.height
        val viewHeight = mViewDataBinding?.nvNestedScroll?.height
        return scrollY >= (contentHeight!! - viewHeight!!)
    }

    private fun banner() {
        val bannerRunnable = object : Runnable {
            override fun run() {
                val current = mViewDataBinding?.vpBanner?.currentItem
                val count = bannerAdapter.itemCount
                if (current != null && count > 0) {
                    mViewDataBinding?.vpBanner?.currentItem = (current + 1) % count
                    mViewModel?.setIndex((current + 1) % count)
                }
                handle.postDelayed(this, 3000) // 每3秒切换一次
            }
        }
        handle.postDelayed(bannerRunnable, 3000)
        mViewDataBinding?.vpBanner?.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mViewModel?.setIndex(position) // 手动滑动时更新索引
            }
        })

    }

    private fun FragmentPaperShowBinding.init() {
        val customDivider = SpacesItemDecoration(30)
        mViewDataBinding?.vpBanner?.adapter = bannerAdapter
        mViewDataBinding?.rvPaperItem?.adapter = paperAdapter
        mViewDataBinding?.rvPaperItem?.addItemDecoration(customDivider)
        mViewDataBinding?.rvPaperItem?.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

    }


    override fun onDestroy() {
        super.onDestroy()
        handle.removeCallbacksAndMessages(null)
    }
}